package Simulation;

public class CustomerArrival extends SimEvent {

	public static long counter = 0;
	private boolean createNextArrival;

	public CustomerArrival(long simTime) {
		this(simTime, true);
	}

	public CustomerArrival(long simTime, boolean createNext) {
		super(simTime);
		createNextArrival = createNext;
	}

	@Override
	public void process() {
		counter++;
		SimState state = SimState.instance;
		// remember how long the queue was on arrival for the statistics
		state.waiting_queue_length.count(state.waiting_queue.size());
		// In the case that all servers are busy
		if (state.getServerBusy()) {
			// check if there is space left or if the system blocks
			if ((DES.MAX_QUEUE_LENGTH == -1)
					|| (state.waiting_queue.size() < DES.MAX_QUEUE_LENGTH)) {
				// Add a new Customer to the waiting queue
				Customer c = new Customer(state.now);
				// If we have a deadline, set the deadline
				if (DES.A3_E2) {
					c.setDeadline(state.now + state.getNextDeadline());
				}
				state.waiting_queue.add(c);
				// Increase the waiting queue length
				state.increaseQueue();

				state.customer_blocked.count(0);
			} else {
				state.customer_blocked.count(1);
			}
			if (createNextArrival) {
				// Create the next CustomerArrival event and insert it in the
				// EventQueue
				state.ec.add(new CustomerArrival(state.now
						+ state.getNextInterArrivalTime()));
			}
		} else {
			// c
			state.customer_blocked.count(0);
			if (createNextArrival) {
				// Create the next CustomerArrival event and insert it in the
				// EventQueue
				state.ec.add(new CustomerArrival(state.now
						+ state.getNextInterArrivalTime()));
			}
			// Create a new ServiceCompletion event and insert it in the
			// EventQueue
			// create a new customer which is getting served at once
			state.ec.add(new ServiceCompletion(state.now
					+ state.getNextServiceCompletionTime(), new Customer(
					simTime, simTime)));
			// Count this customer as satisfied because he was served at once
			// and therefore his deadline did not expire
			state.deadline_expiration.count(0);

			// Set an idle server to busy state
			state.decreaseFreeServers();
		}
	}

}
